package com.lennon.spring.cloud.demo.helloservice;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
@EnableDiscoveryClient
public class HelloServiceApp {

    public static void main(String[] args) {
        SpringApplication.run(HelloServiceApp.class, args);
    }
}

@EnableAutoConfiguration
@RestController
class HelloController {

    @Autowired
    private Environment environment;

    @Autowired
    private Registration registration;

    @GetMapping("/")
    public String index() {
        String serviceId = registration.getServiceId() + environment.getProperty("server.port");

        return serviceId;
    }
}

@Component
class MyHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        long num = System.currentTimeMillis() / 1000;
        if (num % 20 < 10) {
            return Health.down().withDetail("" + num, Long.valueOf(num)).build();
        }
        return Health.up().withDetail("" + num, Long.valueOf(num)).build();
    }
}